/**
 * @author chengqige
 * @copyright turing@大连大学图灵工作室
 * @version 1.0
 * @updated 2022/3/13 23:29
 * @description 用来解析content-type是multipart/form-data的数据，支持自动批量保存图片生成图片链接
 */
const multiparty = require('multiparty')
const { host } = require('../../../config')

const multipart = function (path = './server/img') {
    const baseUrl = host + '/static/'
    return function (req, res, next) {
        let fileArray = []
        const isMulter = req.headers['content-type'] && req.headers['content-type'].includes('multipart/form-data')
        const form = new multiparty.Form({ uploadDir: path })
        if (['GET', 'HEAD'].includes(req.method.toUpperCase()) || !isMulter) {
            next()
            return
        }
        form.parse(req, function (err, fields, files) {
            if (err) {
                if (err.toString().includes('stream')) {
                    res.send('multipart middleware is error: Do not detect requset body at All, did you field request body correctly?')
                } else {
                    res.send(err)
                }
                return
            }
            if (files && Object.keys(files).length) {
                fileArray = files[Object.keys(files)[0]].map(item => {
                    return {
                        filename: item.originalFilename,
                        path: baseUrl + item.path.split('\\').slice(1).join('/')
                    }
                })
            }
            for (let key in fields) {
                if (fields[key][0] === 'undefined') {
                    fields[key] = ''
                    continue
                }
                fields[key] = fields[key][0]
            }
            //判断没有文件
            if (files && files.pic && files.pic[0].size === 0 || fileArray.length === 0) {
                req.body = { ...fields }
            } else {
                req.body = { fileList: fileArray, ...fields }
            }
            next()
        })
    }
}

module.exports = multipart
